import React from "react";
import { getBusinessData, changeContentField } from "src/utils/basic-business";
import { getSearchParams } from "src/utils/index";
import { locationShape, historyShape, storeShape } from "src/propType";
import { Toast, Dialog } from "antd-mobile";
import "./detail.scss";
import { guid, merge, refreshPage, isNormalBrowser, PreviewPdf } from "../../utils";
import axios from "src/api/index";
import { API_URL, PDF_URL, FILE_VIEW, FILE_VIEW_ONLINE } from "src/config";
import Cookies from "js-cookie";
import { getPdfInfo } from "src/api/pqsstartWkInfo";

//表格详情页公共
class Detail extends React.Component {
    workflowRef = React.createRef(null);
    signRef = React.createRef(null);
    constructor(props) {
        super(props);
        const { store, location } = this.props;
        const userData = store.user.userData;
        this.state = {
            loading: false,
            openCode: false,
            ajaxData: {},
            formData: {},
            // 详细页面主键
            pageKid: null,
            // 页面状态
            page: "view",
            primaryKey: "kid",
            // 保存编号规则的数据
            numberRuleData: {},
            pactList: [],
            userPactIds: "",
            pdfShow: false,
            pdfSrc: null,
            userDbName: userData.dbName,
            userProjId: userData.projId,
            defaultConfig: { itemWidth: "33.3%" },
            selectedOptions: null,
            dbName: null,
            baseUrl: null,
            moduleId: null,
            options: null,
            workflowModule: null,
            useWorkflow: null,
            noNumberRule: false,
            needSaveFormData: false,
            title: "",

            pactCode: {
                pactCode0: false, //施工
                pactCode1: false, // 监理审核
                pactCode2: false, // 项目公司
                pactCode3: false,
            },

            hasSubTable: false, //子表
        };
    }

    componentDidMount() {
        const { store, location } = this.props;
        const params = getSearchParams(location.search);
        let { pageKid, pactCode } = this.state;
        let ajaxData = {},
            primaryKey = "kid";
        const selectedOptions = getBusinessData(store, location, "options"),
            dbName = getBusinessData(store, location, "dbName"),
            baseUrl = getBusinessData(store, location, "baseUrl"),
            moduleId = getBusinessData(store, location, "tableId"),
            workflowModule = getBusinessData(store, location, "workflowModule"),
            useWorkflow = getBusinessData(store, location, "useWorkflow");
        const options = selectedOptions.map(opt => {
            return {
                label: opt.label,
                value: opt.value,
            };
        });

        if (params.page === "add") {
            pageKid = ajaxData[primaryKey] = guid();
        } else {
            pageKid = ajaxData[primaryKey] = params.kid;
        }
        this.setState(
            {
                page: params.page,
                selectedOptions,
                dbName,
                baseUrl,
                moduleId,
                options,
                workflowModule,
                useWorkflow,
                pageKid,
                ajaxData: { ...ajaxData },
                pactCode: {
                    ...pactCode,
                    pactCode1: true,
                },
                title: decodeURIComponent(params.title),
            },
            () => {
                if (params.page !== "add") {
                    this.getDetailData(ajaxData);
                }
            },
        );
    }

    setModules = () => {
        const { store, location } = this.props;
        const moduleTableId = getBusinessData(store, location, "singleItem");
        const typeIdOptions = getBusinessData(store, location, "options");
        this.setState({
            formData: {
                moduleId: moduleTableId.tableId,
                moduleName: moduleTableId.modelName,
            },
            moduleTableId,
            typeIdOptions,
        });
    };

    changeTypeListTable = () => {
        let { typeIdOptions, formData, isHaveType } = this.state;
        if (typeIdOptions) {
            if (typeIdOptions.length === 1) {
                isHaveType = typeIdOptions[0].isHaveType;
            } else {
                if (formData.projTypeId > -1) {
                    // 业务类型值存在
                    const findItem = typeIdOptions.find(item => item.value == formData.projTypeId);
                    isHaveType = findItem && findItem.isHaveType;
                }
            }
            this.setState({
                isHaveType,
            });
        }
    };

    initResponseField = () => {
        const { formData, optionOne, selectedOptions, page } = this.state;
        // if (page === "add") {
        const mainWorkPdf = changeContentField(
            optionOne || selectedOptions[0],
            formData,
            "projTypeId",
            page,
            formData.projTypeId,
        );
        const mainWork = mainWorkPdf.replace(/\$\{.*?\|/g, "").replaceAll("}$", "");
        if (mainWorkPdf) {
            /*
            * mainWorkPdf=
            *  致${consName|河北承克高速公路有限公司}$（建设单位）：
            ${monitorName|承德公路工程监理有限责任公司}$（ 项目监理机构）：
            我方承担的${pactName|中国葛洲坝集团股份有限公司承克高速公路施工项目部}$工程，已完成相关准备工作，具备于开工条件，申请于${planstartDate|2025年03月12日}$开工，请予以审批。
            *  */
            /*
            * mainWork=
            * 致河北承克高速公路有限公司（建设单位）：
            承德公路工程监理有限责任公司（ 项目监理机构）：
            我方承担的中国葛洲坝集团股份有限公司承克高速公路施工项目部工程，已完成相关准备工作，具备于开工条件，申请于2025年03月12日开工，请予以审批。
            *  */
            this.setState(
                {
                    formData: {
                        ...formData,
                        mainWorkPdf,
                        mainWork,
                    },
                },
                () => {
                    this.subForm.current?.form.setFieldValue("mainWork", mainWork);
                },
            );
        }
        // }
    };

    // 切换申请类型，改变主表
    setHiddenForm = useDefData => {
        let { formData, childTabType, formItems } = this.state;
        const typeId = formData.typeId || childTabType; // 业务类型
        for (let i = 0; i < formItems.length; i++) {
            const ele = formItems[i];
            ele.hidden = false;
            // 控件显隐
            if (ele.typeIds) {
                if (ele.typeIds.indexOf(typeId) !== -1) {
                    ele.hidden = false; // 显
                } else {
                    ele.hidden = true; //隐
                }
            }

            // 控件隐藏
            if (ele.hiddenTypeIds) {
                if (ele.hiddenTypeIds.indexOf(typeId) !== -1) {
                    ele.hidden = true; // 隐
                }
            }

            //动态配置label
            if (ele.isConfigLabel) {
                ele.label = ele["label" + typeId] || ele["labelDef"];
            }
            // 是否使用默认值登录人，或者是wbs树
            if (useDefData) {
                if (ele.useDefAssign) {
                    for (const usKey in ele.useDefAssign) {
                        const elconst = ele.useDefAssign[usKey];
                        formData[usKey] = useDefData[elconst] || (elconst === "wbsId" ? 0 : null);
                    }
                }
            }

            //  使用默认当前时间
            if (ele.useDefTimeObj) {
                formData[ele.name] = this.formatDateTime(ele[ele.useDefTimeObj] || new Date());
            }
        }
        const hasSubTable = !formItems.find(item => item.name === "subTable")?.hidden;
        this.setState({
            formData: {
                ...formData,
            },
            formItems: [...formItems],
            hasSubTable,
        });
        // this.setHiddenFormAfter && this.setHiddenFormAfter()
    };

    formatDateTime = (date, type) => {
        if (this.page != "add") {
            date = new Date(date);
        }
        if (typeof date !== "string") {
            date = new Date(date);
            let year = date.getFullYear() + "";
            let month =
                date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1 + "";
            let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate() + "";
            let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours() + "";
            let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes() + "";
            let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds() + "";
            if (type == 1 || type == "yyyy年MM月dd日") {
                return year + "年" + month + "月" + day + "日 ";
            } else if (
                type == 2 ||
                type == "yyyy-MM-dd HH:mm:ss" ||
                type == "yyyy-MM-dd hh:mm:ss"
            ) {
                return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
            } else if (
                type == 3 ||
                type == "yyyy年MM月dd日 HH时mm分ss秒" ||
                type == "yyyy年MM月dd日 hh时mm分ss秒"
            ) {
                return (
                    year +
                    "年" +
                    month +
                    "月" +
                    day +
                    "日 " +
                    hour +
                    "时:" +
                    minute +
                    "分:" +
                    second +
                    "秒"
                );
            } else {
                return year + "-" + month + "-" + day;
            }
        } else {
            return date;
        }
    };

    /**
     * 保存 新增 或编辑的数据 需要包含 ref=form
     *  包含 beforeSave 钩子 return true 则保存
     */
    save = async (type = null, tips) => {
        const url = this.getSaveURL();
        const form = this.subForm.current?.form;
        let values = form.getFieldsValue();
        for (let key in values) {
            //处理下拉onchange数据格式
            if (Object.prototype.toString.call(values[key]) === "[object Object]") {
                values = {
                    ...values,
                    ...values[key],
                };
            }
        }
        try {
            await form.validateFields(values);
        } catch (error) {
            if (error.errorFields.length) {
                Toast.show({
                    icon: "fail",
                    content: error.errorFields[0].errors[0],
                });
                return;
            }
        }
        Promise.resolve(this.beforeSave && this.beforeSave()).then(res => {
            if (this.beforeSave && !res) return;
            const data = this.handleFormDataBeforeSave(values);
            axios({
                method: "post",
                url,
                data,
            }).then(res => {
                if (res.success) {
                    Toast.show({
                        icon: "success",
                        content: tips || "保存成功",
                        duration: 1000,
                    });
                    refreshPage();
                    this.props.history.go(-1);
                } else {
                    Toast.show({
                        icon: "fail",
                        content: res.msg || "操作失败",
                        duration: 1000,
                    });
                }
            });
        });
    };

    ///合并表单填写数据
    handleFormDataBeforeSave = values => {
        const { formData, ajaxData, isNoChangeStateId, page } = this.state;
        let change = { ...formData, ...values };
        merge(change, ajaxData);
        if (isNoChangeStateId) {
            // 开工标准化，审核后编辑，不更新状态
            delete change.stateId;
            delete change.stateName;
            if (page === "add") {
                delete change.moduleId;
            }
        }
        return change;
    };

    //提交审核,直接审核
    commit = async () => {
        const form = this.subForm.current?.form;
        let values = form.getFieldsValue();
        for (let key in values) {
            //处理下拉onchange数据格式
            if (Object.prototype.toString.call(values[key]) === "[object Object]") {
                values = {
                    ...values,
                    ...values[key],
                };
            }
        }
        try {
            await form.validateFields(values);
        } catch (error) {
            if (error.errorFields.length) {
                Toast.show({
                    icon: "fail",
                    content: error.errorFields[0].errors[0],
                });
                return;
            }
        }

        Promise.resolve(this.beforeSave && this.beforeSave()).then(res => {
            if (this.beforeSave && !res) return;
            //所有数据在审核流程界面提交
            const formData = this.handleFormDataBeforeSave(values);
            this.setState({
                formData,
            });
            this.workflowRef.current.visibleCb(true);
        });
    };

    commitSign = () => {
        this.signRef?.current.setShow(true);
    };

    toViewPdf = async record => {
        const isView = await Dialog.confirm({ content: "是否预览pdf" });
        if (!isView) return;

        Toast.show({
            icon: "loading",
            content: "",
            duration: FILE_VIEW_ONLINE ? 2000 : 0,
        });
        const res = await getPdfInfo(record.kid);
        const { code, data, msg } = res;
        const hasFile = data && Array.isArray(data) ? data.length : data;
        if (code === 200 && hasFile) {
            const fileUrl = data && (data.pdfName || data.pdfPath || data.svrFullPath);
            const url = (PDF_URL + fileUrl).replace(/\\/g, "/");

            // if (!isNormalBrowser()) {
            //     const url = `${API_URL}/wpfile/downloadPdf?dbName=GPMSPQS&recordId=${record.kid}&title=${record.moduleName}.pdf`;
            //     PreviewPdf(url);
            //     return;
            // }

            if (FILE_VIEW_ONLINE) {
                // 在线预览方式
                // let viewUrl = `${url}&fullfilename=${record.kid}.pdf&isApp=1`;
                PreviewPdf(fileUrl);
            } else {
                //downLoadFile
                axios({
                    method: "GET",
                    customError: true,
                    _ingore: true,
                    url: FILE_VIEW,
                    params: {
                        fileName: `${record.kid}.pdf`,
                        cookies: `CRBIMSSOJWT=${Cookies.get("CRBIMSSOJWT")}`,
                        url,
                        isApp: 1,
                    },
                }).then(res => {
                    if (res.msg === "SUCCESS") {
                        Toast.show({
                            icon: "success",
                            content: "",
                        });
                        res.data && window.open(res.data);
                    } else {
                        Toast.show({
                            icon: "fail",
                            content: res.msg,
                        });
                    }
                });
            }
        } else {
            Toast.show({
                icon: "fail",
                content: hasFile ? msg : "PDF文件不存在",
                afterClose: () => {},
            });
            return;
        }
    };

    getSaveURL() {
        const { suffixNo, baseUrl, page, customUrl, mySelfUrl } = this.state;
        if (suffixNo !== undefined) {
            return baseUrl + suffixNo + "_" + page;
        }
        return (customUrl !== undefined && customUrl[page]) || mySelfUrl || baseUrl + "_" + page;
    }

    getDetailURL(suffix) {
        const { baseUrl, customUrl } = this.state;
        return (customUrl !== undefined && customUrl[suffix.replace(/_/g, "")]) || baseUrl + suffix;
    }

    getDetailData = async ajaxData => {
        const res = await axios({
            method: "get",
            url: this.getDetailURL("_query_one"),
            data: ajaxData,
        });
        if (res.success) {
            const formData = res.data;
            const { page, pactCode } = this.state;
            if (formData) {
                if (page === "sign" && formData.stateId === 1) {
                    //施工
                    pactCode.pactCode0 = true;
                    pactCode.pactCode1 = true; //施工-是
                    pactCode.pactCode2 = false; // 监理审核-否
                    pactCode.pactCode3 = false; // 项目公司-否
                } else if (page === "sign" && formData.stateId === 2) {
                    //监理
                    pactCode.pactCode0 = true;
                    pactCode.pactCode1 = false; //施工-是
                    pactCode.pactCode2 = true; // 监理审核-否
                    pactCode.pactCode3 = false; // 项目公司-否
                } else if (page === "sign" && formData.stateId === 3) {
                    //审核
                    pactCode.pactCode0 = true;
                    pactCode.pactCode1 = false; //施工-是
                    pactCode.pactCode2 = false; // 监理审核-否
                    pactCode.pactCode3 = true; // 项目公司-否
                } else {
                    pactCode.pactCode0 = true;
                    pactCode.pactCode1 = true;
                }

                this.setState(
                    {
                        formData,
                        pactCode: {
                            ...pactCode,
                        },
                    },
                    () => {
                        this.aftergetDetailData && this.aftergetDetailData(formData);
                    },
                );
            }
        } else {
            Toast.show({
                icon: "fail",
                content: "数据加载错误，请刷新重试",
            });
        }
    };

    commitCallBack = () => {
        this.props.history.go(-1);
        refreshPage();
    };

    commitSignCallBack = flag => {
        if (flag === "agree" && this.state.needSaveFormData) {
            this.setState(
                {
                    page: "edit",
                    isNoChangeStateId: true,
                },
                () => {
                    this.save();
                },
            );
        }
    };
}

Detail.propTypes = {
    store: storeShape,
    history: historyShape,
    location: locationShape,
};

export default Detail;
